package com.bw.controller.information;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bw.entity.information.PiLinkman;
import com.bw.entity.information.PiMaterial;
import com.bw.entity.user.TbUser;
import com.bw.req.TbUserRes;
import com.bw.resp.ResponseResult;
import com.bw.service.information.IPiMaterialService;

import com.bw.utils.excel.ExcelUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import net.sf.excelutils.ExcelException;
import net.sf.excelutils.ExcelUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  原材料前端控制器
 * </p>
 *
 * @author lizhengqian
 * @since 2020-06-16
 */
@RestController
@RequestMapping("/material")
public class PiMaterialController {
    @Autowired
    private IPiMaterialService iPiMaterialService;

    private final Logger logger= LoggerFactory.getLogger(PiMaterialController.class);
    /**
     * 原材料列表模糊
     */
    @PostMapping("list/{page}/{size}")
    public ResponseResult list(@PathVariable("page") int page, @PathVariable("size") int size, @RequestBody PiMaterial piMaterial) { //参数json字符串
        logger.info("原材料列表查询");
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            PageHelper.startPage(page, size);//开启分页查询
            QueryWrapper queryWrapper = new QueryWrapper();
            if (piMaterial.equals("")) {
                queryWrapper.like("name", "%" + piMaterial.getName() + "%");//模糊查询原材料的名字
                queryWrapper.or();
                queryWrapper.like("chemical", "%" + piMaterial.getName() + "%");//模糊查询原材料的化学元素叫法
                queryWrapper.or();
                queryWrapper.like("code", "%" + piMaterial.getName() + "%");//模糊查询原材料的编号
            }
            queryWrapper.ne("isdelete",0);
            List<PiMaterial> users = iPiMaterialService.list(queryWrapper);//列表查询
            System.out.println(users.toString());
            PageInfo pageInfo = new PageInfo(users);//pagehelper封装好的分页实体类，将数据放进去
            result.setResult(pageInfo);
        } catch (Exception e) {
            logger.info("查询失败,{}",e.toString());
            result.setSuccess(false);
            result.setMessage("查询失败:" + e.toString());
        }
        logger.info("原材料列表查询结束");
        return result;
    }
    /**
     * 原材料删除
     */
    @DeleteMapping("del/{id}")
    public ResponseResult del(@PathVariable("id") Integer id) {
        logger.info("原材料删除");
        ResponseResult result = ResponseResult.SUCCESS();
        try {

            PiMaterial pp= iPiMaterialService.getById(id);
            pp.setIsdelete(0);
            iPiMaterialService.saveOrUpdate(pp);
            result.setMessage("删除成功");
        } catch (Exception e) {
            logger.info("删除失败,{}",e.toString());
            result.setSuccess(false);
            result.setMessage("删除失败:" + e.toString());
        }
        logger.info("原材料删除结束");
        return result;
    }
    /**
     * 原材料查找明细
     */
    @GetMapping("get/{id}")
    public ResponseResult get(@PathVariable("id") Integer id) {
        logger.info("原材料查找明细");
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            PiMaterial mm=iPiMaterialService.getById(id);
            result.setResult(mm);
            result.setMessage("查找成功");
        } catch (Exception e) {
            logger.info("查找明细失败,{}",e.toString());
            result.setSuccess(false);
            result.setMessage("查找失败:" + e.toString());
        }
        logger.info("原材料查找明细结束");
        return result;
    }
    /**
     * 原材料保存接口
     */
    @PostMapping("save")
    public ResponseResult save(@RequestBody PiMaterial piMaterial) { //参数json字符串
        logger.info("原材料保存接口");
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            //判断原材料是否存在
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("name", piMaterial.getName());
            List<PiMaterial> pi = iPiMaterialService.list(queryWrapper);
            if (pi.size() > 0 && null == piMaterial.getId()) {//如果查询原材料名存在则提示用户
                result.setSuccess(false);
                result.setMessage("保存失败:原材料已存在");
                return result;
            }
            iPiMaterialService.saveOrUpdate(piMaterial);//添加或修改原材料
            result.setMessage("保存成功");
        } catch (Exception e) {
            logger.info("原材料保存失败,{}",e.toString());
            result.setSuccess(false);
            result.setMessage("保存失败:" + e.toString());
        }
        logger.info("原材料保存结束");
        return result;
    }
    /**
     * 原材料导入
     */
    @PostMapping("/importExcel")
    public ResponseResult importExcel(MultipartFile file){
        logger.info("原材料导入");
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            String ext = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."), file.getOriginalFilename().length());
            List<Map> mapList = ExcelUtil.readExcel(ext, file.getInputStream());
            String jsonString = JSON.toJSONString(mapList);
            List<PiMaterial> list = JSON.parseArray(jsonString, PiMaterial.class);
            iPiMaterialService.saveBatch(list);
        }catch (Exception e){
            logger.info("原材料导入失败,{}",e.toString());
            result.setMessage("导入失败"+e.toString());
            result.setSuccess(false);
        }
        logger.info("原材料导入结束");
        return result;
    }
    /**
     * 原材料导出
     */
    @GetMapping("/exportExcel")
    public void exportExcel(HttpServletResponse response) throws IOException, ExcelException {
        logger.info("原材料导出");
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.ne("isdelete",0);
        List<PiMaterial> list = iPiMaterialService.list(queryWrapper);

        response.setHeader("Content-Type","application/vnd.ms-excel;charset=UTF-8");
        response.setHeader("Content-Disposition","attachment;filename="+new String("原材料数据".getBytes(),"iso-8859-1")+".xls");
        ClassPathResource classPathResource = new ClassPathResource("xls/material.xls");
        InputStream inputStream = classPathResource.getInputStream();//获取excel的模板

        ExcelUtils.addValue("list",list);

        ExcelUtils.export(inputStream,ExcelUtils.getContext(),response.getOutputStream());//第一个参数：模板的流。第三个：输出到哪
        logger.info("原材料导出结束");
    }
}
